package com.personal.portal.admin.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.personal.portal.common.entity.Result;
import com.personal.portal.admin.entity.DictCategory;
import com.personal.portal.admin.entity.DictItem;
import com.personal.portal.admin.mapper.DictCategoryMapper;
import com.personal.portal.admin.mapper.DictItemMapper;
import com.personal.portal.admin.service.DictItemService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 字典值服务实现类
 * 
 * @author zhanghui
 * @version 1.0.0
 * @since 2025-11-10
 */
@Service
public class DictItemServiceImpl implements DictItemService {

    @Resource
    private DictItemMapper dictItemMapper;
    
    @Resource
    private DictCategoryMapper dictCategoryMapper;

    @Override
    public DictItem queryById(Long id) {
        validateId(id);
        return dictItemMapper.selectOneById(id);
    }

    @Override
    public DictItem queryByEntity(DictItem dictItem) {
        QueryWrapper queryWrapper = buildQueryWrapper(dictItem);
        return dictItemMapper.selectOneByQuery(queryWrapper);
    }

    @Override
    public List<DictItem> queryList(DictItem dictItem) {
        QueryWrapper queryWrapper = buildQueryWrapper(dictItem);
        return dictItemMapper.selectListByQuery(queryWrapper);
    }

    @Override
    public Result.PageResult<DictItem> queryPage(int pageNum, int pageSize, DictItem dictItem) {
        QueryWrapper queryWrapper = buildQueryWrapper(dictItem);
        Page<DictItem> paginate = dictItemMapper.paginate(pageNum, pageSize, queryWrapper);
        return new Result.PageResult<>(paginate.getRecords(), paginate.getTotalRow(), pageNum, pageSize);
    }

    @Override
    public int insert(DictItem dictItem) {
        validateDictItem(dictItem);
        return dictItemMapper.insert(dictItem);
    }

    @Override
    public int update(DictItem dictItem) {
        if (dictItem.getId() == null) {
            throw new IllegalArgumentException("字典值ID不能为空");
        }
        validateId(dictItem.getId());
        validateDictItem(dictItem);
        
        DictItem existing = dictItemMapper.selectOneById(dictItem.getId());
        if (existing == null) {
            throw new IllegalArgumentException("字典值信息不存在");
        }
        
        return dictItemMapper.update(dictItem);
    }

    @Override
    public int deleteById(Long id) {
        validateId(id);
        
        DictItem existing = dictItemMapper.selectOneById(id);
        if (existing == null) {
            throw new IllegalArgumentException("字典值信息不存在");
        }
        
        return dictItemMapper.deleteById(id);
    }

    @Override
    public List<Long> deleteBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("ID列表不能为空");
        }

        List<Long> successIds = new ArrayList<>();
        List<Long> failedIds = new ArrayList<>();

        for (Long id : ids) {
            try {
                validateId(id);
                
                DictItem existing = dictItemMapper.selectOneById(id);
                if (existing == null) {
                    failedIds.add(id);
                    continue;
                }

                int result = dictItemMapper.deleteById(id);
                if (result > 0) {
                    successIds.add(id);
                } else {
                    failedIds.add(id);
                }
            } catch (Exception e) {
                failedIds.add(id);
            }
        }

        if (!successIds.isEmpty()) {
            return successIds;
        } else {
            throw new IllegalArgumentException("批量删除失败");
        }
    }

    @Override
    public List<DictItem> queryByCategoryId(Long categoryId) {
        validateCategoryId(categoryId);
        
        DictItem dictItem = new DictItem();
        dictItem.setCategoryId(categoryId);
        return queryList(dictItem);
    }

    @Override
    public List<DictItem> queryByCategoryCode(String categoryCode) {
        if (StringUtils.isBlank(categoryCode)) {
            throw new IllegalArgumentException("分类代码不能为空");
        }
        
        // 首先根据分类代码查询分类ID
        QueryWrapper categoryQueryWrapper = new QueryWrapper();
        categoryQueryWrapper.eq(DictCategory::getCode, categoryCode);
        DictCategory dictCategory = dictCategoryMapper.selectOneByQuery(categoryQueryWrapper);
        
        if (dictCategory == null) {
            throw new IllegalArgumentException("字典分类不存在，分类代码：" + categoryCode);
        }
        
        // 根据分类ID查询字典值列表
        DictItem dictItem = new DictItem();
        dictItem.setCategoryId(dictCategory.getId());
        return queryList(dictItem);
    }

    /**
     * 验证字典值信息
     */
    private void validateDictItem(DictItem dictItem) {
        if (dictItem == null) {
            throw new IllegalArgumentException("字典值信息不能为空");
        }
        if (dictItem.getCategoryId() == null) {
            throw new IllegalArgumentException("分类ID不能为空");
        }
        if (StringUtils.isBlank(dictItem.getName())) {
            throw new IllegalArgumentException("字典名称不能为空");
        }
        if (StringUtils.isBlank(dictItem.getCode())) {
            throw new IllegalArgumentException("字典代码不能为空");
        }
        if (StringUtils.isBlank(dictItem.getValue())) {
            throw new IllegalArgumentException("字典值不能为空");
        }
        // 验证字典代码格式（只能包含字母、数字、下划线）
//        if (!dictItem.getCode().matches("^[a-zA-Z0-9_]+$")) {
//            throw new IllegalArgumentException("字典代码只能包含字母、数字、下划线");
//        }
    }

    /**
     * 验证ID
     */
    private void validateId(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的字典值ID");
        }
    }

    /**
     * 验证分类ID
     */
    private void validateCategoryId(Long categoryId) {
        if (categoryId == null || categoryId <= 0) {
            throw new IllegalArgumentException("无效的分类ID");
        }
    }

    /**
     * 构建查询条件
     */
    private QueryWrapper buildQueryWrapper(DictItem dictItem) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DictItem::getId, dictItem.getId(), dictItem.getId() != null);
        queryWrapper.eq(DictItem::getCategoryId, dictItem.getCategoryId(), dictItem.getCategoryId() != null);
        queryWrapper.like(DictItem::getName, dictItem.getName(), StringUtils.isNotEmpty(dictItem.getName()));
        queryWrapper.like(DictItem::getCode, dictItem.getCode(), StringUtils.isNotEmpty(dictItem.getCode()));
        queryWrapper.like(DictItem::getValue, dictItem.getValue(), StringUtils.isNotEmpty(dictItem.getValue()));
        queryWrapper.like(DictItem::getDescription, dictItem.getDescription(), StringUtils.isNotEmpty(dictItem.getDescription()));
        queryWrapper.eq(DictItem::getStatus, dictItem.getStatus(), dictItem.getStatus() != null);

        queryWrapper.orderBy(DictItem::getSortOrder, true);
        queryWrapper.orderBy(DictItem::getName, true);
        queryWrapper.orderBy(DictItem::getId, true);
        return queryWrapper;
    }
}